//
//  InfoList.m
//  Trading365
//
//  Created by yifei tong on 12-1-10.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "InfoList.h"


@implementation InfoList
@synthesize search;
@synthesize searchDisplayController;
@synthesize p_search,infoTitle;
@synthesize responseParams;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{    
	self = [super init];
        
    responseParams = [[NSMutableArray alloc] initWithCapacity:0];
    //m_bIsBack = NO;
	if(self)
	{
	}
	
	return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{    
    [search release];
    //[responseParams release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self init];
    [super viewDidLoad];
    [self.view setBackgroundColor:BACKGROUND_COLOR];

    // Do any additional setup after loading the view from its nib.
    getflag = YES;
    _isSearching = NO;
    self.search.showsCancelButton=NO;
    p_search=[NSString stringWithFormat:@""];
    self.title = infoTitle;
    
    //search button
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                      target:self 
                                      action:@selector(find)];
    self.navigationItem.rightBarButtonItem = searchButton;
    
    [searchButton release];
 
    UIButton *barRetBut = [[UIButton alloc] initWithFrame:CGRectMake(5.0, 27.0, 50.0, 30.0)];
    [barRetBut setTitle:@" 返回" forState:UIControlStateNormal];
    UIFont *font              = [UIFont systemFontOfSize:14];
    barRetBut.titleLabel.font = font;
    UIImage *barRetImageNormal = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_NORMAL];
    [barRetBut setBackgroundImage:barRetImageNormal forState:UIControlStateNormal];
    UIImage *barRetImagePressed = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_PRESS];
    [barRetBut setBackgroundImage:barRetImagePressed forState:UIControlStateHighlighted];
    [barRetBut addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    

    self.navigationItem.leftBarButtonItem  =  [[UIBarButtonItem alloc]initWithCustomView:barRetBut];

    self.navigationItem.leftBarButtonItem.enabled = NO;


    //search bar
//    UISearchBar *mySearchBar = [[UISearchBar alloc] init];
    search = [[UISearchBar alloc] init];
	[search setScopeButtonTitles:[NSArray arrayWithObjects:nil,nil]];
	search.delegate = (id)self;
	[search setAutocapitalizationType:UITextAutocapitalizationTypeNone];
	[search sizeToFit];
        
    //如何修改UISearchBar的scopeBar的背景颜色
    search.tintColor = NAVIGATION_BAR_COLOR;  
    search.backgroundColor=[UIColor clearColor];  

    [self changePlaceholder];

	self.tableView.tableHeaderView = search;
	/*
	 fix the search bar width problem in landscape screen
	 */
	if (UIInterfaceOrientationLandscapeRight == [[UIDevice currentDevice] orientation] ||
		UIInterfaceOrientationLandscapeLeft == [[UIDevice currentDevice] orientation])
	{
		self.tableView.tableHeaderView.frame = CGRectMake(0.f, 0.f, 480.f, 44.f);
	}
	else
	{
		self.tableView.tableHeaderView.frame = CGRectMake(0.f, 0.f, 320.f, 44.f);
	}
	/*
	 set up the searchDisplayController programically
	 */
	searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:search contentsController:self];
	[self setSearchDisplayController:searchDisplayController];
	[searchDisplayController setDelegate:(id)self];
	[searchDisplayController setSearchResultsDataSource:self];
    
//	[search release];
    self.tableView.scrollEnabled = YES;
    [self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
//    self.tableView.style=UITableViewStyleGrouped;
    
//    self.view.userInteractionEnabled = YES;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    search=nil;
    //responseParams = nil;
    infoTitle = nil;
}
- (void)viewDidDisappear:(BOOL)animated
{
  
}
- (void)viewWillAppear:(BOOL)animated {

	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view delegate
//Jason-子类需要复写该方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //
}

#pragma mark - Table view data source
//Jason-子类需要复写该方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier: CellIdentifier] autorelease];
    }
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [responseParams count];
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
        
    NSString *tmp=[[NSString alloc] initWithFormat:@"%@",searchString];
    p_search = tmp;
//	p_search = [NSString stringWithString:searchString];
    
    // Return YES to cause the search result table view to be reloaded.
    return NO;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
    //    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
    //	 [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

    // Return YES to cause the search result table view to be reloaded.
    return NO;
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
	
    //     Bob: Because the searchResultsTableView will be released and allocated automatically, so each time we start to begin search, we set its delegate here.
	[self.searchDisplayController.searchResultsTableView setDelegate:self];
}


- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
    //Hide the search bar
	[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (getflag ==  NO){
        getflag = YES;
    }
    [self doSearch];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    if (self.search.showsCancelButton==NO)
        self.search.showsCancelButton=YES;

    [self changePlaceholder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    self.search.showsCancelButton=NO;
    [search resignFirstResponder];
    //    [self refreshData];
}

#pragma mark - text delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGFloat keyboardHeight = 216.0f;
    if (self.view.frame.size.height - keyboardHeight <= textField.frame.origin.y + textField.frame.size.height) {
        CGFloat y = textField.frame.origin.y - (self.view.frame.size.height - keyboardHeight - textField.frame.size.height - 5);
        [UIView beginAnimations:@"srcollView" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.275f];
        self.view.frame = CGRectMake(self.view.frame.origin.x, -y, self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

//该方法为点击虚拟键盘Return，要调用的代理方法：隐藏虚拟键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

//该方法为完成输入后要调用的代理方法：虚拟键盘隐藏后，要恢复到之前的文本框地方
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:@"srcollView" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.275f];
    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    
    [textField resignFirstResponder];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    
}

-(BOOL) textViewShouldReturn:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}


#pragma mark - 
#pragma mark - my function
-(void)goBack
{
    [[self navigationController] popViewControllerAnimated:YES];
}

-(void)find
{
    [self changePlaceholder];
    [searchDisplayController.searchBar setSelectedScopeButtonIndex:0];
    [searchDisplayController setActive:YES animated:YES];
}

//Jason-子类需要复写该方法
- (void)doSearch{
    if(p_search.length<1)
        return;
    
    self.search.showsCancelButton=NO;
    
    _isSearching = YES;
    [responseParams removeAllObjects];
    
    [search resignFirstResponder];
    [self.searchDisplayController setActive:NO];
    [self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
    
}


//Jason-子类需要复写该方法
-(void)refreshData
{    
//    NSLog(@"InfoList refreshData.");
//    [[[TaskManager Share] GetTaskByType:GetInfoList Delegate:self] Excute];
}

//Jason-子类需要复写该方法
-(void) getMoreData
{
//    NSLog(@"InfoList getMoreData.");
}

-(void) OnPreExcute
{
    [super OnPreExcute];
    spinner = [[TKLoadingAnimationView alloc] initWithFrame:CGRectMake(140, 155, 30, 30) 
                                tkLoadingAnimationViewStyle:TKLoadingAnimationViewStyleCarton];
	
	[self.view addSubview:spinner];
	[spinner startAnimating];
	[spinner release];
}

//Jason-子类需要复写该方法
-(void) DoInBackground
{
    //
}

-(void) OnPostExcute
{    
    [super OnPostExcute];
    self.navigationItem.leftBarButtonItem.enabled=YES;
    [spinner stopAnimating];
}

- (void)changePlaceholder
{
    self.search.showsCancelButton = YES;
    for(id ctl in [self.search subviews])
    {
        if([ctl isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)ctl;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
        
        if ([ctl isKindOfClass:[UITextField class]]){
            UITextField *txf = (UITextField *)ctl;
            [txf setPlaceholder:@"请输入搜索关键字"];
        }
    }    
}

@end
